#include "CppUnitTestRunner.h"
#include "MyListener.h"
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/portability/Stream.h>
#include <cppunit/SourceLine.h>

CppUnitTestRunner::CppUnitTestRunner()
{
	m_pController = new CPPUNIT_NS::TestResult();

	m_pResultCollector = new CPPUNIT_NS::TestResultCollector();
	m_pController->addListener(m_pResultCollector);

	m_pMyListener = new MyListener();
	m_pController->addListener(m_pMyListener);

	m_pPlugInManager = new CPPUNIT_NS::PlugInManager();
	m_pPlugInManager->addListener(m_pController);

	m_pTestRunner = new CPPUNIT_NS::TestRunner();
	m_pFailure = NULL;
}

CppUnitTestRunner::~CppUnitTestRunner()
{
	/*delete m_pPlugInManager;
	delete m_pMyListener;
	delete m_pResultCollector;
	delete m_pController;
	delete m_pTestRunner;*/
}

void CppUnitTestRunner::LoadTests(const char* p_pszPluginPath)
{
	m_pPlugInManager->load(p_pszPluginPath);
	m_pTests = CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest();
	m_pTestRunner->addTest(m_pTests);
}

void CppUnitTestRunner::UnloadTests(const char* p_pszPluginPath)
{
	m_pPlugInManager->unload(p_pszPluginPath);
	m_pTests = NULL;
}

bool CppUnitTestRunner::RunTest(const char* p_pszTestPath)
{
	try	{
		m_pResultCollector->reset();
		m_pTestRunner->run(*m_pController, p_pszTestPath);
	}
	catch (std::invalid_argument& )	{
		CPPUNIT_NS::stdCOut()  <<  "Failed to resolve test path: "  
			<<  "\n";
	}

	if (m_pResultCollector->testFailuresTotal() != 0) {
		//	Test failed - get error details
		m_pFailure = m_pResultCollector->failures()[0];
		return false;
	}

	return true;
}

CPPUNIT_NS::Test* CppUnitTestRunner::GetTestRoot()
{
	return m_pTests;
}